//
//  LYSetViewController.m
//  IPhoneX适配
//
//  Created by 训网高 on 2018/5/2.
//  Copyright © 2018年 训网高. All rights reserved.
//

#import "LYSetViewController.h"
#import "LYSetTableViewCell.h"
#import "FileTool.h"

#define CachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) firstObject]
@interface LYSetViewController () <UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSArray *subTitleArray;
@property (nonatomic, strong) NSArray *imageArray;
@property (nonatomic, assign) NSInteger totalSize;
@end

@implementation LYSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"设置";
    [self hideTabbar];
    //初始化
    self.view.backgroundColor = UIColorFromRGB(0xf3f3f3);
    //设置数据源
    self.titleArray = [NSArray arrayWithObjects:@"鼓励我们",@"检查更新",@"清除缓存",@"新版本功能介绍", nil];
    self.imageArray = [NSArray arrayWithObjects:@"set_encourage",@"set_update",@"set_clearCache",@"set_function", nil];
    //获取文件夹尺寸
    //文件夹非常小，如果文件非常大
    [FileTool getFileSize:CachePath completion:^(NSInteger totalSize) {
        self->_totalSize = totalSize;
        [self.tableView reloadData];
        
    }];
    [self creatTableView];
    
    
    UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 30)];
    backButton.backgroundColor = [UIColor redColor];
    //设置UIButton的图像
    [backButton setImage:[UIImage imageNamed:@"white_back_little"] forState:UIControlStateNormal];
    //给UIButton绑定一个方法，在这个方法中进行popViewControllerAnimated
    [backButton addTarget:self action:@selector(leftItemClick) forControlEvents:UIControlEventTouchUpInside];
    //然后通过系统给的自定义BarButtonItem的方法创建BarButtonItem
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:backButton];
    //覆盖返回按键
    self.navigationItem.leftBarButtonItem = backItem;
}
- (void)leftItemClick {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)creatTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, Height_NavBar, SCREEN_WIDTH, 200) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    //注册cell
    [self.tableView registerClass:[LYSetTableViewCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:self.tableView];
    
    //退出登录按钮
    UIButton *exitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    exitButton.frame = CGRectMake(20, CGRectGetMaxY(self.tableView.frame)+20, SCREEN_WIDTH-40, 50);
    [exitButton setTitle:@"退出登录" forState:UIControlStateNormal];
    exitButton.titleLabel.font = [UIFont systemFontOfSize:20.0];
    exitButton.layer.cornerRadius = 5;
    exitButton.layer.masksToBounds = YES;
    exitButton.backgroundColor = UIColorFromRGB(0x08c0dd);
    [exitButton addTarget:self action:@selector(exitButtonClick) forControlEvents:UIControlEventTouchUpInside];
    //如果是登录状态显示退出登录按钮，不是登录状态直接不显示
    //此处需要做判断
    [self.view addSubview:exitButton];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LYSetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (!cell) {
        cell = [[LYSetTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.mainImageView.image = [UIImage imageNamed:self.imageArray[indexPath.row]];
    cell.titleLabel.text = self.titleArray[indexPath.row];
    if (indexPath.row == 0) {
        cell.subTitleLabel.text = @"体验如何？去平分吧";
    } else if (indexPath.row == 1) {
        cell.subTitleLabel.text = @"";
    } else if (indexPath.row == 2) {
        DLog(@"%@",[self sizeStr]);
        if ([self sizeStr] == nil) {
            cell.subTitleLabel.text = @"0 MB";
        } else {
            cell.subTitleLabel.text = [self sizeStr];
        }
    } else {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager GET:@"http://itunes.apple.com/lookup?id=1148842778" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            //加载进度
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //请求成功
            DLog(@"%@",responseObject);
            NSDictionary *dic = (NSDictionary *)responseObject;
            DLog(@"请求结果 ---- %@",dic);
            NSDictionary *resultDic = [dic[@"results"] lastObject];
            DLog(@"----%@",resultDic);
            dispatch_async(dispatch_get_main_queue(), ^{
                cell.subTitleLabel.text = [NSString stringWithFormat:@"游学宝版本号：%@",resultDic[@"version"]];
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //请求失败
            [self showHint:@"请求失败"];
        }];
    }
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        //鼓励我们
        NSString *str = @"https://itunes.apple.com/us/app/%E6%B8%B8%E5%AD%A6%E5%AE%9D/id1148842778?mt=8";
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:@{} completionHandler:nil];
    } else if (indexPath.row == 1) {
        //检查更新
        // 获取当前app版本号
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        CFShow((__bridge CFTypeRef)(infoDictionary));
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        //获取appstore上面的版本号
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager GET:@"http://itunes.apple.com/lookup?id=1148842778" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            //加载进度
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //请求成功
            DLog(@"%@",responseObject);
            NSDictionary *dictionary = (NSDictionary *)responseObject;
            for (NSDictionary *dic in dictionary[@"results"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    DLog(@"----%@",dic[@"version"]);
                    if ([app_Version isEqualToString:dic[@"version"]]) {
                        [self showHint:@"当前已是最新版本"];
                    } else {
                        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"有最新版本，是否更新" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                        alertView.delegate = self;
                        alertView.tag = 1000;
                        [alertView show];
                        [self.view addSubview:alertView];
                    }
                });
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //请求失败
        }];
    } else if (indexPath.row == 2) {
        //清除缓存
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"确认清除缓存" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.delegate = self;
        alertView.tag = 1001;
        [alertView show];
        [self.view addSubview:alertView];
    } else {
        //新版本功能介绍
    }
}

#pragma mark ---- 退出登录
- (void)exitButtonClick {
//    [GXUserService userLoginoutcallBack:^(GXResponse *response) {
//        if (response.isSuccess) {
//            [self logoutAction];
//        }
//        else{
//            [self.findVC showToastAlertWithMessage:@"退出登录失败，请联系管理员！"];
//            GXLoginViewController * loginVC = [[GXLoginViewController alloc]init];
//            [self.navigationController pushViewController:loginVC animated:YES];
//        }
//    }];
}


- (void)logoutAction
{
    
    __weak typeof(self) weakSelf = self;
    
    [weakSelf showHudInView:weakSelf.view hint:NSLocalizedString(@"setting.logoutOngoing", @"loging out...")];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf hideHud];
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
//            [[RCIMClient sharedRCIMClient] logout];
//            [GXUserModel shareInstance].isLogined = NO;
//            [GXUserModel shareInstance].token = @"";
//            [GXUserModel shareInstance].userName = @"";
//            [GXUserModel shareInstance].password = @"";
//            [GXUserModel shareInstance].RCToken = @"";
//            [GXUserModel shareInstance].unReadNoticeCount = @"0";
//            [GXUserModel saveLoginUserInfo];
            UITabBarItem *item = self.tabBarController.tabBar.items[1];
            item.badgeValue = nil;
            [weakSelf.navigationController popViewControllerAnimated:NO];
            weakSelf.navigationController.tabBarController.selectedIndex=0;
            
        });
    });
}

//获取缓存尺寸字符串
- (NSString*)sizeStr
{
    NSInteger totalSize = _totalSize;
    NSString * sizeStr;
    if (totalSize >1000*1000) {
        CGFloat sizeF = totalSize/1000.0/1000.0;
        sizeStr = [NSString stringWithFormat:@"%.1fMB",sizeF];
    }
    else if (totalSize>1000)
    {
        CGFloat sizeF = totalSize/1000.0;
        sizeStr = [NSString stringWithFormat:@"%.1fKB",sizeF];
    }
    else if (totalSize>0)
    {
        sizeStr = [NSString stringWithFormat:@"%.ldB",(long)totalSize];
    }
    
    return sizeStr;
    
}

#pragma mark ---- 清楚缓存
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        
    }else{
        if (alertView.tag == 1000) {
            //更新
            NSString *str = @"https://itunes.apple.com/us/app/%E6%B8%B8%E5%AD%A6%E5%AE%9D/id1148842778?mt=8";
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:@{} completionHandler:nil];
        } else {
            //清空缓存
            //删除文件夹里所有文件
            [FileTool removeDirectoryPath:CachePath];
            
            //删除缓存后，文件大小显示为0
            _totalSize = 0;
            [self.tableView reloadData];
        }
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
